package com.qcby.types.util;



import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.qcby.types.exception.IResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;


@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MessageUtils {

    private static final MessageSource MESSAGE_SOURCE = SpringUtil.getBean(MessageSource.class);

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        //LocaleContextHolder.getLocale() 来源于浏览器中的语言
        String message = null;
        try {
            message = MESSAGE_SOURCE.getMessage(code, args, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            //Nothing to do
        }

        if (StrUtil.isBlank(message)) {
            message = StrUtil.indexedFormat(code, args);
        }
        return message;
    }

    public static String getMessageFromResponse(IResponse response, Object... params) {
        String message = response.getMessage();
        if (StrUtil.isNotBlank(message)) {
            message = MessageUtils.message(message, params);
        }
        return message;
    }

}
